package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController {
    @Reference
    UserService userService;
    @RequestMapping("/loginSuccess")
    public String loginSuccess(){
      return "redirect:http://localhost:83/pages/main.html";
    }
    @RequestMapping("/loginFail")
    public String loginFail(){
        return "redirect:http://localhost:83/login.html?message=logFail";
    }
    @RequestMapping("/getUsername")
    @ResponseBody
    public Result getUsername(){
        try {
            SecurityContext context = SecurityContextHolder.getContext();
            Authentication authentication = context.getAuthentication();
            User user = (User) authentication.getPrincipal();
            String username = user.getUsername();
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS,username);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_USERNAME_FAIL);
        }

    }
    @RequestMapping("/findMenu")
    @ResponseBody
    public Result findMenu(String username){
        try {
            List<Map<String,Object>>menuList=userService.findMenu(username);
            for (Map<String, Object> map : menuList) {
                System.out.println(map);
            }
            return new Result(true,MessageConst.GET_MENU_SUCCESS,menuList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_MENU_FAIL);
        }

    }
}
